package com.xr.sunnyday.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xr.sunnyday.dao.CheckgroupDao;
import com.xr.sunnyday.entity.PageResult;
import com.xr.sunnyday.entity.QueryPageBean;
import com.xr.sunnyday.exception.SunnydayException;
import com.xr.sunnyday.pojo.CheckGroup;
import com.xr.sunnyday.service.CheckgroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckgroupService.class)
public class CheckgroupServiceImp implements CheckgroupService {

    @Autowired
    private CheckgroupDao checkgroupDao;

    @Override
    public List<CheckGroup> findAll() {
        return checkgroupDao.findAll();
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //3.开启查询,Page是分页信息
        Page<CheckGroup> page = checkgroupDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }
//    添加
    @Override
    @Transactional
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //1.先添加项目组
        checkgroupDao.add(checkGroup);
        //2.获取项目组id
        Integer checkGroupId = checkGroup.getId();
        //如果用户勾选了就添加到第三章表t_checkgroup_checkitem
        if(null!=checkitemIds){
            for(Integer checkitemId:checkitemIds){
                //把他们关联到第三章表
                checkgroupDao.addCheckGroupChenckItem(checkGroupId,checkitemId);
            }
        }
    }

    @Override
    public List<Integer> findCheckItemIdBYfindCheckGroupId(int checkGroupId) {
        return checkgroupDao.findCheckItemIdBYfindCheckGroupId(checkGroupId);
    }

    @Override
    @Transactional
    public void update(CheckGroup checkGroup, int[] checkitemIds) {
        checkgroupDao.update(checkGroup);
        checkgroupDao.deleteCheckGroupCheckItem(checkGroup.getId());
        if (null!=checkitemIds){
            for(Integer checkitemId:checkitemIds){
                checkgroupDao.addCheckGroupChenckItem(checkGroup.getId(),checkitemId);
            }
        }
    }

    @Override
    @Transactional
    public void delete(int checkGroupId) {

        //看有没有被上一级的表使用
        int id = checkgroupDao.findSetmealCountByGroupId(checkGroupId);
        if (id>0){
            //2.如果第三张表中有值，则抛出异常
            throw new SunnydayException("该检查组关联着套餐，不能删除");
        }
        //没有就解除跟下一层的关系
        checkgroupDao.deleteCheckGroupCheckItem(checkGroupId);
        //最后才可以删自己
        checkgroupDao.delete(checkGroupId);
    }

    @Override
    public CheckGroup findByid(int checkGroupId) {
        return checkgroupDao.findByid(checkGroupId);
    }


}
